package com.boss.example.filter;

import java.io.IOException;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.boss.example.entity.vo.UUUsersVO;
import com.boss.example.entity.vo.FunsVO;

@WebFilter(filterName = "SafeFilter",urlPatterns = "/*")
public class SafeFilter implements Filter{

    /**
     * 对Filter初始化
     * @param arg0
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }

    /**
     * 在Filter被销毁前回收某些资源
     */
    @Override
    public void destroy() {
    }

    /**
     * 实现过滤功能
     * @param arg0
     * @param arg1
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1,
                         FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) arg0;
        HttpServletResponse res = (HttpServletResponse) arg1;
        String uri = req.getRequestURI();
        // 对静态资源做放行处理
        if (uri.endsWith(".js") || uri.endsWith(".css") || uri.endsWith(".gif")) {
            chain.doFilter(arg0, arg1);
        } else {
            // 对用户登录资源做放行
            if (uri.indexOf("login") != -1 || uri.indexOf("userLogin") != -1) {
                chain.doFilter(arg0, arg1);
            } else {
                HttpSession session = req.getSession();
                UUUsersVO user = (UUUsersVO)session.getAttribute("user");
                List<FunsVO> funs = user.getFun();
                // 开关
                boolean flag = false;
                for (FunsVO f : funs) {
                    // 判断当前访问的 URI 是否在功能数据中包含
                    if (uri.indexOf(f.getFunUrl()) != -1) {
                        flag = true;
                        break;
                    }
                }
                // 根据开关的值来进行跳转
                if (flag) {
                    chain.doFilter(arg0, arg1);
                } else {
                    res.sendRedirect("roleerror");
                }
            }
        }
    }

}
